package oakclub.service;

import nf.fr.eraasoft.pool.ObjectPool;
import oakclub.global.Enums;
import oakclub.global.Config;
import oakclub.global.Container;
import oakclub.global.Context;
import oakclub.global.DateFormatter;
import oakclub.thrift.scribe.LogEntry;
import oakclub.thrift.scribe.scribe;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

public class ScribeService
{
    private String prefix = Config.get("scribe.prefix");
    private String fieldSeparator = Config.get("scribe.separator.field");
    private String lineSeparator = Config.get("scribe.separator.line");

    private ObjectPool<scribe.Client> clientPool = (ObjectPool<scribe.Client>) Container.getComponent(Enums.Component.SCRIBE_CLIENT);
    private final Logger logger = LoggerFactory.getLogger(ScribeService.class);

    public enum Type
    {
        LOGIN(1), CHAT(7), SEND_STICKER(18);

        private final int val;

        private Type(int val)
        {
            this.val = val;
        }

        public int val()
        {
            return this.val;
        }
    }

    private LogEntry createLogEntry(Type type, Object ... args)
    {
        Date now = new Date();
        String category = this.prefix + '_' + DateFormatter.getFormatter("yyyyMMdd").format(now);

        String message = "";
        message += UUID.randomUUID().toString() + this.fieldSeparator;
        message += DateFormatter.getFormatter("yyyy-MM-dd HH:mm:ss").format(now) + this.fieldSeparator;
        message += type.val() + this.fieldSeparator;
        message += Context.get().getPlatformId() + this.fieldSeparator;
        message += this.fieldSeparator;
        message += this.fieldSeparator;
        message += this.fieldSeparator;
        message += StringUtils.join(args, this.fieldSeparator);
        message += this.lineSeparator;

        return new LogEntry(category, message);
    }

    private void log(Type type, Object ... args)
    {
        scribe.Client client = null;
        try
        {
            client = this.clientPool.getObj();
            client.Log(Arrays.asList(this.createLogEntry(type, args)));
        }
        catch(Exception e)
        {
            this.logger.warn("scribe log failed", e);
        }
        finally
        {
            if(client != null)
            {
                this.clientPool.returnObj(client);
            }
        }
    }

    public void login(long userId, int platformId, String deviceName, String osVersion)
    {
        this.log(Type.LOGIN, userId, platformId, deviceName, osVersion);
    }

    public void chat(long userId)
    {
        this.log(Type.CHAT, userId);
    }

    public void sendSticker(long userId, long targetId, String image)
    {
        this.log(Type.SEND_STICKER, userId, targetId, image);
    }
}
